package com.xlx.ui.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xlx.ui.domain.DTO.UserDTO;
import com.xlx.ui.domain.MO.User;
import com.xlx.ui.domain.VO.ResultBody;
import com.xlx.ui.mapper.UserMapper;
import com.xlx.ui.service.error.errorImpl.BizException;
import com.xlx.ui.service.error.errorImpl.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @author: 张川
 * @date: 2021-03-18 22:23
 */
@Slf4j
@Service
public class AdminUserService {

    @Autowired
    private UserMapper userMapper;

    public User login(String username, String password) {
        Example example = Example.builder(User.class)
                .where(Sqls.custom()
                        .andEqualTo("name", username)
                        .andEqualTo("password", SecureUtil.sha256("xlx" + password))
                        .andEqualTo("auth", 0)).build();
        List<User> users = userMapper.selectByExample(example);
        if (!users.isEmpty()) {
            User user = users.get(0);
            if (!user.getState()) {
                throw new BizException(ResponseCodeEnum.USER_DISABLE);
            }
            return user;
        } else {
            throw new BizException(ResponseCodeEnum.USER_NULL);
        }
    }

    public User getUser(String name) {
        Example example = Example.builder(User.class).where(Sqls.custom().andEqualTo("name", name)).build();
        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()) {
            throw new BizException(ResponseCodeEnum.USER_NOT_EXIST);
        }
        return users.get(0);
    }

    public User getInfo(String token) {
        String name;
        try {
            name = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new BizException(ResponseCodeEnum.SIGNATURE_NOT_MATCH);
        }
        User user = this.getUser(name);
        if (user == null) {
            throw new BizException(ResponseCodeEnum.USER_NOT_EXIST);
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new BizException(ResponseCodeEnum.SIGNATURE_NOT_MATCH);
        }
        return user;
    }

    public ResultBody getAll(UserDTO userDTO) {
        Example userExample = new Example(User.class);
        Example.Criteria criteria = userExample.createCriteria();
        if (StrUtil.isNotBlank(userDTO.getName())) {
            criteria.andEqualTo("name", userDTO.getName());
        }
        if (userDTO.getState() != null) {
            criteria.andEqualTo("state", userDTO.getState());
        }
        if (StrUtil.isNotBlank(userDTO.getSort())) {
            if (userDTO.getSort().startsWith("-")) {
                userExample.orderBy("id").desc();
            } else {
                userExample.orderBy("id");
            }
        }
        List<User> users = userMapper.selectByExampleAndRowBounds(userExample, new RowBounds(userDTO.getPage() - 1, userDTO.getLimit()));
        JSONObject object = new JSONObject();
        object.put("items", users);
        object.put("total", users.size());
        return ResultBody.success(object);
    }

    public boolean add(UserDTO userDTO) {
        Example email = Example.builder(User.class).where(Sqls.custom().andEqualTo("email", userDTO.getEmail())).build();
        List<User> users = userMapper.selectByExample(email);
        if(!users.isEmpty()){
            throw new BizException(ResponseCodeEnum.EMAIL_NOT_NULL);
        }
        User user = new User();
        user.setEmail(userDTO.getEmail());
        user.setCreateDate(new Date());
        user.setAuth(userDTO.getAuth());
        user.setName(userDTO.getName());
        user.setState(userDTO.getState());
        user.setPassword(SecureUtil.sha256("xlx123456"));
        userMapper.insertSelective(user);
        return true;
    }
}
